package com.songcha.library_common.ui.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.ImageView
import com.songcha.library_common.R
import com.songcha.library_common.util.dp2px

@SuppressLint("AppCompatCustomView")
class CustomCheckBox
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0,
    defRes: Int = 0
): ImageView(context,attrs,defStyle,defRes){
    fun interface IOnCheckListener{
        fun onCheck(isCheck:Boolean)
    }

    private var mListener:IOnCheckListener?=null
    private var mCheckImage:Drawable?=null
    private var mUnCheckImage:Drawable?=null

    companion object{
        private val DEFAULT_SIZE=24.dp2px()
    }

    private var mIsCheck=false


    init{
        initView(context,attrs)
    }


    private fun initView(context:Context,attrs: AttributeSet?){
        scaleType=ScaleType.CENTER_CROP

        if(attrs!=null){
            val ta=context.obtainStyledAttributes(attrs, R.styleable.CustomCheckBox)
            mIsCheck=ta.getBoolean(R.styleable.CustomCheckBox_checkbox_ischeck,false)
            mCheckImage=ta.getDrawable(R.styleable.CustomCheckBox_checkbox_check_image)
            mUnCheckImage=ta.getDrawable(R.styleable.CustomCheckBox_checkbox_uncheck_image)
            ta.recycle()
        }

        setOnClickListener{
            mIsCheck=!mIsCheck
            update()
            mListener?.let {
                it.onCheck(mIsCheck)
            }
        }

        update()

    }

    fun setOnCheckListener(listener: IOnCheckListener){
        this.mListener = listener
    }


    private fun update(){
        if(mIsCheck){
            if(mCheckImage!=null)
                setImageDrawable(mCheckImage!!)
            else
                setImageResource(R.mipmap.common_icon_checked)
        }else{
            if(mUnCheckImage!=null)
                setImageDrawable(mUnCheckImage!!)
            else
                setImageResource(R.mipmap.common_icon_uncheck)
        }
    }

    fun isCheck():Boolean{
        return mIsCheck
    }

    fun setIsCheck(isCheck:Boolean){
        if(isCheck!=mIsCheck){
            mIsCheck=isCheck
            update()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthMode=MeasureSpec.getMode(widthMeasureSpec)
        val heightMode=MeasureSpec.getMode(heightMeasureSpec)
        if(widthMode!=MeasureSpec.EXACTLY || heightMode!=MeasureSpec.EXACTLY){
            setMeasuredDimension(DEFAULT_SIZE, DEFAULT_SIZE)
        }
    }



}